<template>
  <el-dialog
    v-model="isVisible"
    title="文件设置"
    width="50%"
    :close="handleClose"
  >
    <p class="text-red mb-4 text-bold">
      tips:如果同时上传了文件和填写了外部文件下载地址,优先使用上传的文件
      {{ file_outside_url }} -
    </p>
    <span class="text-black block mb-2">方式一 上传文件附件到服务器</span>
    <el-upload
      ref="upload"
      :action="`${BASE_URL}upload`"
      :limit="1"
      :on-error="onError"
      :on-success="onSuccess"
      :on-remove="onRemove"
      :file-list="fileList"
      class="mb-10"
    >
      <template #trigger>
        <el-button type="primary">
          select file
        </el-button>
      </template>
      <template #tip>
        <div class="el-upload__tip text-red">
          limit 1 file, new file will cover the old file
        </div>
      </template>
    </el-upload>
    <span class="text-black block mb-2">方式二 填写外部下载地址</span>
    <el-input
      v-model="form.file_outside_url"
      placeholder="请填写文件下载地址"
    />
    <template #footer>
      <div>
        <el-button
          @click="handleClose"
        >
          取消
        </el-button>
        <el-button
          type="primary"
          @click="handleConfrim"
        >
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup>
import { ref, watch } from 'vue'
import { useVModel } from '@vueuse/core'
import config from '@/utils/config'
import notification from '@/utils/dict-notification'

const { BASE_URL } = config

const form = ref({
  file_id: '',
  file_outside_url: '',
})

const props = defineProps({
  title: {
    type: String,
    default: '文件设置',
  },
  modelValue: {
    type: Boolean,
    require: true,
    default: false,
  },
  fileList: {
    type: Array,
    require: true,
    default: () => [],
  },
  file_outside_url: {
    type: String,
    default: '',
  },
})

const emits = defineEmits(['update:modelValue', 'onConfirm'])
const isVisible = useVModel(props, 'modelValue', emits)

const onError = (err) => {
  const { message } = err
  const error = JSON.parse(message)
  notification(error.code, error.message)
}

const onRemove = () => {
  form.value.file_id = ''
}

const onSuccess = (response) => {
  const [file] = response
  if (file)
    form.value.file_id = file.id
}

const reset = () => {
  form.value = {
    file_id: '',
    file_outside_url: '',
  }
}
const handleConfrim = () => {
  emits('onConfirm', form.value)
  isVisible.value = false
  reset()
}

const handleClose = () => {
  isVisible.value = false
  reset()
}

watch(isVisible, (val) => {
  if (val)
    form.value.file_outside_url = props.file_outside_url
}, {
  deep: true,
  immediate: true,
})
</script>
